//
//  SpecialEventDetailController.m
//  yilutongxing
//
//  Created by T&J on 2017/11/10.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import <QMUITips.h>
#import "SpecialEventDetailController.h"
#import "RPSpecialEventBean.h"
#import "DzyImgPicker.h"
#import "PhotosView.h"
#import "CommonDefine.h"
#import "SinglelineTextFormViewController.h"
#import "IQActionSheetPickerView.h"
#import "TimeTools.h"

#define URL_Specialevent @"/api/specialEvents"

@interface SpecialEventDetailController ()<DzyImgDelegate, SinglelineTextFormViewControllerDelegate,
                                            IQActionSheetPickerViewDelegate,
                                            NetworkUtilsDelegate>
@property (strong, nonatomic) IBOutlet UITableViewCell *record_row;
@property (strong, nonatomic) IBOutlet UITableViewCell *report_row;

@property(strong, nonatomic) NSArray *row_title_arr;
@property (nonatomic) NSMutableDictionary *pickerIndexCache;
@property(strong, nonatomic) NSMutableArray *picCacheArr;
@property(strong, nonatomic) NSMutableDictionary *picCacheDic;
@property (nonatomic, strong) NSMutableDictionary *imgPickerDic;//图片选择控件缓存
@property(nonatomic, strong) NSMutableDictionary *imgUrlCacheDic;//图片url缓存

@property(nonatomic,copy) NSString *leaveRecord;
@property(nonatomic,copy) NSString *reprot;
@end

@implementation SpecialEventDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //样式设置
    self.title = @"新增特殊事件";
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"]
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self
                                                                           action:@selector(backAction)];
    UIBarButtonItem *submit = [[UIBarButtonItem alloc] initWithTitle:@"保存"
                                                               style:UIBarButtonItemStyleDone
                                                              target:self
                                                              action:@selector(saveAction)];
    self.navigationItem.rightBarButtonItem = submit;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    if (_eventBean) {
        self.title = @"修改特殊事件";
        self.imgUrlCacheDic[@"leaveRecord"] = _eventBean.leaveRecord;
        self.imgUrlCacheDic[@"reprot"] = _eventBean.reprot;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UI逻辑
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveAction{
    NSMutableDictionary *data = [self.eventBean mj_keyValuesAdd];
    data[@"leaveRecord"] = self.leaveRecord;
    data[@"reprot"] = self.reprot;
    
    if (self.eventBean.id) {
        [[YZENetwork sharedInstace]putRequestWithUrl:[BASE stringByAppendingString:URL_Specialevent]
                                          parameters:data
                                            delegate:nil
                                          requestTag:1
                                        successBlock:^(id responseObject)
         {
             [QMUITips hideAllToastInView:self.view animated:YES];
             [QMUITips showInfo:@"保存成功！" inView:self.view hideAfterDelay:2];
             if ([self.delegate respondsToSelector:@selector(backSpecialevent:index:)]) {
                 [self.delegate backSpecialevent:self.eventBean index:self.indexPath];
             }
             [self backAction];
         }];
    }
    else {
        [[YZENetwork sharedInstace]postRequestWithUrl:[BASE stringByAppendingString:URL_Specialevent]
                                          parameters:data
                                            delegate:nil
                                          requestTag:1
                                        successBlock:^(id responseObject)
         {
             [QMUITips hideAllToastInView:self.view animated:YES];
             [QMUITips showInfo:@"上传成功！" inView:self.view hideAfterDelay:2];
             if ([self.delegate respondsToSelector:@selector(backSpecialevent:index:)]) {
                 [self.delegate backSpecialevent:self.eventBean index:self.indexPath];
             }
             [self backAction];
         }];
    }
    [QMUITips showLoadingInView:self.view];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==2 || indexPath.row==4) {
        return 158;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row==2) {
        cell = self.record_row;
    }
    else if(indexPath.row==4){
        cell = self.report_row;
    }
    else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    
    if (indexPath.row!=2 && indexPath.row!=4) {
        cell.textLabel.text = self.row_title_arr[indexPath.row];
    }
    
    //渲染数据
    NSInteger index = ROWINDEX(indexPath);
    if (self.eventBean) {
        switch (indexPath.row) {
            case 0:{
                NSString *time = self.eventBean.eventTime?self.eventBean.eventTime:@" ";
                time = [TimeTools getYearMonthDayWithTimeString:time];
                cell.detailTextLabel.text = time;
                
            }
                break;
            case 1:{
                cell.detailTextLabel.text = self.eventBean.againEvent?self.eventBean.againEvent:@" ";
            }
                break;
            case 2:{
                [self layoutDzyView:cell rowIndex:index];
                if (![self.picCacheDic objectForKey:[NSNumber numberWithInteger:index]]) {
                    if (((NSString*)self.imgUrlCacheDic[@"leaveRecord"]).length>0) {
                        [self requestPictures:self.eventBean.leaveRecord?self.eventBean.leaveRecord:@"" ctrlIndex:index];
                    }
                }
            }
                break;
            case 3:{
                cell.detailTextLabel.text = self.eventBean.otherEvent?self.eventBean.otherEvent:@" ";
            }
                break;
            case 4:{
                [self layoutDzyView:cell rowIndex:index];
                if (![self.picCacheDic objectForKey:[NSNumber numberWithInteger:index]]) {
                    if (((NSString*)self.imgUrlCacheDic[@"reprot"]).length>0) {
                        [self requestPictures:self.eventBean.reprot?self.eventBean.reprot:@"" ctrlIndex:index];
                    }
                }
            }
                break;
            default:
                break;
        }
    }
    
    return cell;
}


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==1 || indexPath.row==3) {
        SinglelineTextFormViewController *vc = [SinglelineTextFormViewController new];
        vc.delegate = self;
        vc.indexPath = indexPath;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row==0){
        IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
        [picker setTag:ROWINDEX(indexPath)];
        [picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
        [picker show];
    }
}

//创建图片控件
-(void)layoutDzyView:(UITableViewCell*)cell rowIndex:(NSInteger)rowindex{
    if (self.pickerIndexCache[[NSNumber numberWithInteger:rowindex]]) {
        return;
    }
    self.pickerIndexCache[[NSNumber numberWithInteger:rowindex]] = @1;
    DzyImgPicker *picker = [[DzyImgPicker alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 115) andParentV:self andMaxNum:1];
    picker.tag = rowindex;
    picker.dzyImgDelegate = self;
    picker.collectionView.scrollEnabled=NO;
    UIView *backView = [cell viewWithTag:1];
    [backView addSubview:picker];
    [self.imgPickerDic setObject:picker forKey:[NSNumber numberWithInteger:rowindex]];
}
//发起图片请求
- (void)requestPictures:(NSString*)urlArrStr ctrlIndex:(NSInteger)index{
    if (![urlArrStr isNotEmpty]) {
        return;
    }
    NSMutableArray *urlArr = [[urlArrStr componentsSeparatedByString:@","] mutableCopy];
    //逆序遍历清除空元素
    for (int i=(int)urlArr.count-1; i>=0; i--) {
        NSString *element = urlArr[i];
        if (element.length==0) {
            [urlArr removeObjectAtIndex:i];
        }
    }
    if (urlArr.count==0) {
        return;
    }
    NSMutableArray *tempImageArr = [NSMutableArray array];
    for (NSString *url in urlArr) {
        NSURL *ourl = [NSURL URLWithString:url];
        UIImageView *iv = [[UIImageView alloc] init];
        [self.picCacheArr addObject:iv];
        [iv sd_setImageWithURL:ourl completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image) {
                [tempImageArr addObject:image];
                if (tempImageArr.count == urlArr.count) {
                    DzyImgPicker *picker = [self.imgPickerDic objectForKey:[NSNumber numberWithInteger:index]];
                    [picker setImages:tempImageArr];
                }
            }
        }];
    }
    [self.picCacheDic setObject:@1 forKey:[NSNumber numberWithInteger:index]];
}

#pragma mark - IQActionSheetPickerViewDelegate
-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectDate:(NSDate *)date{
    NSIndexPath *ip = DEROWINDEX(pickerView.tag);
    UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:ip];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    cell.detailTextLabel.text=[formatter stringFromDate:date];
    self.eventBean.eventTime = cell.detailTextLabel.text;
}

#pragma mark - 图片选择控件代理 DzyImgDelegate
- (void)getBase64Images:(NSArray *)imgData index:(NSInteger)tag{
    NSIndexPath *ip = DEROWINDEX(tag);
    if (ip.row==2){
        self.leaveRecord = [imgData[0] mutableCopy];
    }
    else if(ip.row==4){
        self.reprot = [imgData[0] mutableCopy];
    }
}

#pragma mark - SinglelineTextFormViewControllerDelegate
- (void)backData:(NSString *)content identifier:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 1:{
            self.eventBean.againEvent = content;
        }
            break;
        case 3:{
            self.eventBean.otherEvent = content;
        }
        default:
            break;
    }
    [self.tableView reloadData];
}

#pragma mark - 数据配置
- (NSArray *)row_title_arr{
    if (!_row_title_arr) {
        _row_title_arr = @[@"时间", @"再次入院事件", @"placeholder1", @"其它事件", @"placehoalder2"];
    }
    return _row_title_arr;
}

- (NSMutableArray *)picCacheArr{
    if (!_picCacheArr) {
        _picCacheArr = [NSMutableArray array];
    }
    return _picCacheArr;
}

- (NSMutableDictionary *)picCacheDic{
    if (!_picCacheDic) {
        _picCacheDic = [NSMutableDictionary dictionary];
    }
    return _picCacheDic;
}

- (NSMutableDictionary *)pickerIndexCache{
    if (!_pickerIndexCache) {
        _pickerIndexCache = [NSMutableDictionary  dictionary];
    }
    return _pickerIndexCache;
}

- (NSMutableDictionary *)imgPickerDic{
    if (!_imgPickerDic) {
        _imgPickerDic = [NSMutableDictionary dictionary];
    }
    return _imgPickerDic;
}

- (RPSpecialEventBean *)eventBean{
    if (!_eventBean) {
        _eventBean = [RPSpecialEventBean new];
    }
    return _eventBean;
}

- (NSMutableDictionary *)imgUrlCacheDic{
    if (!_imgUrlCacheDic) {
        _imgUrlCacheDic = [NSMutableDictionary dictionary];
    }
    return _imgUrlCacheDic;
}

#pragma mark - 网络代理
- (void)OnFinishWithRequestTag:(int)tag{
    [QMUITips hideAllToastInView:self.view animated:YES];
}

@end
